import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes';
import store from '@/store'

Vue.use(VueRouter)



// 解决多次点击进行同一个地址跳转报错问题
let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { });
    }
}

let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { });
    }
}

const router = new VueRouter(
    {
        routes,
        // 设置跳转后默认回到页面顶端
        scrollBehavior(to, from, savedPosition) {
            return { y: 0 }
        }
    }
)

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    if (token) {
        if (to.path == '/login' || to.path == 'register') {
            next('/home')
        } else {
            if (store.state.user.userInfo.name) {
                next()
            } else {
                try {
                    await store.dispatch("getUserInfo");
                    next()
                } catch (error) {
                    await store.dispatch("loginOut");
                    next("/login")
                }
            }
        }
    } else {
        if (to.path.indexOf("trade") != -1 || to.path.indexOf("pay") != -1 || to.path.indexOf("center") != -1) {
            next("/login?redirect=" + to.path)
        } else {
            next()
        }

    }
})

export default router 